<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave">
            <searchrevealing>
                <el-tabs v-model="activeTab" @tab-change="tabChange">
                    <el-tab-pane label="待接收" name="DJS" />
                    <el-tab-pane label="已接收" name="YJS" />
                    <el-tab-pane label="已入库" name="YRK" />
                    <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="104px">
                        <el-form-item label="商品名称" prop="styleName">
                            <el-input v-model="queryParams.styleName" placeholder="请输入商品名称" clearable
                                style="width: 220px" @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="类目" prop="categoryIdList">
                            <el-cascader v-model="queryParams.categoryIdList" :options="options" style="width: 220px"
                                filterable clearable ref="categoryRef" placeholder="请选择" :props="props" />
                        </el-form-item>
                        <el-form-item label="商品编码/69码" prop="content">
                            <el-input v-model="queryParams.content" placeholder="请输入" clearable maxlength="20"
                                style="width: 220px" @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="供应商" prop="supplierId">
                            <el-select v-model="queryParams.supplierId" placeholder="请选择供应商" clearable filterable
                                v-selectLoad="selectLoad" :teleported="false" :fit-input-width="true" remote
                                :remote-method="searchQuery" class="supplierSelect" style="width: 220px"
                                :loading="supplierQueryLoading" @clear="handleClear">
                                <el-option v-for="dict in supplierNameOptions" :key="dict.value" :label="dict.label"
                                    :value="dict.value">
                                </el-option>
                                <template v-if="supplierLoading">
                                    <div class="supplierSelect_icon">
                                        <el-icon class="el-select-loading__icon">
                                            <Loading />
                                        </el-icon>
                                        <span class="el-select-loading__tips">{{ "正在加载" }}</span>
                                    </div>
                                </template>
                                <template #loading>
                                    <svg class="circular" viewBox="0 0 50 50">
                                        <circle class="path" cx="25" cy="25" r="20" fill="none" />
                                    </svg>
                                </template>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="对接群名" prop="groupName">
                            <el-input v-model="queryParams.groupName" placeholder="请输入" clearable style="width: 220px"
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="部门类型" prop="types">
                            <el-select v-model="queryParams.types" placeholder="请选择部门类型" clearable filterable
                                @change="(e: string) => { departmentTypeChange('type', e) }" style="width: 220px">
                                <el-option v-for="dict in departmentTypeList" :key="dict.deptId" :label="dict.deptName"
                                    :value="dict.deptId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="部门名称" prop="recruiterDeptId">
                            <el-select v-model="queryParams.recruiterDeptId" placeholder="请选择部门名称" clearable filterable
                                @change="deptChange" style="width: 220px">
                                <el-option v-for="dict in deptList" :key="dict.deptId" :label="dict.deptName"
                                    :value="dict.deptId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="人员名称" prop="recruiterUserId">
                            <el-select v-model="queryParams.recruiterUserId" placeholder="请选择人员名称" clearable filterable
                                style="width: 220px">
                                <el-option v-for="dict in recruiterList" :key="dict.userId" :label="dict.nickName"
                                    :value="dict.userId" />
                            </el-select>
                        </el-form-item>
                        <!-- 待接收 已接收可看 -->
                        <el-form-item label="审批通过时间" prop="putTime" v-if="activeTab != 'YRK'">
                            <el-date-picker value-format="YYYY-MM-DD" v-model="putTime" type="daterange"
                                @change="pricingPickerChange" start-placeholder="开始时间" end-placeholder="结束时间" clearable
                                style="width: 220px" />
                        </el-form-item>
                        <!-- 已入库可看 -->
                        <el-form-item label="入库时间" prop="storeTime" v-if="activeTab == 'YRK'">
                            <el-date-picker value-format="YYYY-MM-DD" v-model="storeTime" type="daterange"
                                @change="storePickerChange" start-placeholder="开始时间" end-placeholder="结束时间" clearable
                                style="width: 220px" />
                        </el-form-item>
                        <!-- 待接收可看 -->
                        <el-form-item label="创建时间" prop="createTime" v-if="activeTab == 'DJS'">
                            <el-date-picker value-format="YYYY-MM-DD" v-model="createTime" type="daterange"
                                @change="createPickerChange" start-placeholder="开始时间" end-placeholder="结束时间" clearable
                                style="width: 220px" />
                        </el-form-item>
                        <!-- 已接收 已入库可看 -->
                        <el-form-item label="接收时间" prop="receiveTime" v-if="activeTab !== 'DJS'">
                            <el-date-picker value-format="YYYY-MM-DD" v-model="receiveTime" type="daterange"
                                @change="receivePickerChange" start-placeholder="开始时间" end-placeholder="结束时间" clearable
                                style="width: 220px" />
                        </el-form-item>
                        <!-- 待接收可看 -->
                        <el-form-item label="品牌" prop="brandName" v-if="activeTab == 'DJS'">
                            <el-input v-model="queryParams.brandName" placeholder="请输入商品名称" clearable
                                style="width: 220px" @keyup.enter="handleQuery" />
                        </el-form-item>
                        <!-- 待接收 已接收可看 -->
                        <el-form-item label="合同状态" prop="sellStatus" v-if="activeTab != 'YRK'">
                            <el-select v-model="queryParams.sellStatus" placeholder="请选择" clearable filterable
                                @change="deptChange" style="width: 220px">
                                <el-option v-for="dict in sellStatusList" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                        <!-- 已接收 已入库可看 -->
                        <el-form-item label="接收人" prop="recipient" v-if="activeTab !== 'DJS'">
                            <el-input v-model="queryParams.recipient" placeholder="请输入商品名称" clearable
                                style="width: 220px" @keyup.enter="handleQuery" />
                        </el-form-item>
                    </el-form>
                    <div class="form_button">
                        <el-button type="primary" @click="handleQuery" :loading="queryLoading">查询</el-button>
                        <el-button @click="resetQuery" :loading="queryLoading">重置</el-button>
                    </div>
                </el-tabs>
            </searchrevealing>
        </transition>
        <el-card shadow="never">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"
                        :name="activeTab == 'DJS' ? '在仓商品管理待接收列表' : activeTab == 'YJS' ? '在仓商品管理已接收列表' : '在仓商品管理已入库列表'"
                        @updateColumn="getColmun"></right-toolbar>
                </el-row>
            </template>
            <el-table v-loading="loading" row-key="id" :data="tableData" border @header-dragend="dragEnd">
                <el-table-column v-for="(item, index) in commodityManage" :key="index" :label="item.label"
                    align="center" :prop="item.prop" show-overflow-tooltip :fixed="item.fixed" :width="item.width">
                    <template #default="scope">
                        <image-preview v-if="item.prop == 'productImage'" :src="scope.row.productImage" :width="50"
                            :height="50" />
                        <div v-if="item.prop == 'hmMechanismsList'">
                            <div>{{ computedMechanism(scope.row.hmMechanismsList && scope.row.hmMechanismsList[0] ||
                                null,
                                '一') }}
                            </div>
                            <div>{{ computedMechanism(scope.row.hmMechanismsList && scope.row.hmMechanismsList[1] ||
                                null,
                                '二') }}
                            </div>
                            <div>{{ computedMechanism(scope.row.hmMechanismsList && scope.row.hmMechanismsList[2] ||
                                null,
                                '三') }}
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" fixed="right">
                    <template #default="scope">
                        <el-button link size="small" type="primary" @click="handleInfo(scope.row, '查看详情')"
                            v-if="activeTab !== 'DJS'">查看详情</el-button>
                        <el-button link size="small" type="primary" @click="handleInfo(scope.row, '接收')"
                            v-else>接收</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="tableTotal > 0" :total="tableTotal" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="paginationChange" />
        </el-card>
        <el-drawer v-model="isAddDrawer" :title="AddFormTitle" direction="rtl" size="70%" :close-on-click-modal="false">
            <AddForm v-if="isAddDrawer" @onSubmit="AddFormSubmit" :title="AddFormTitle" :AddFormId="AddFormId"
                :disabledName="disabledName" />
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import { loginSupplierList } from '@/api/group/supplier/index'
import { getCategoryLists } from '@/api/group/productOutbound'
import { commissionaireList, commissionaireReceive } from '@/api/group/productOutbound/index'
import { getUserList, getSystemList } from '@/api/group/qualityControl'
import { type Action } from 'element-plus'
import AddForm from '../investDepartment/commodityManage/addform/index.vue'
const { proxy } = getCurrentInstance() as any;
const commodityManage = ref()
const columnData = ref()
const activeTab = ref('DJS');
const queryFormRef = ref();
const showSearch = ref(true);
const loading = ref(false);
const options = ref()
const props = {
    multiple: true
}

const isAddDrawer = ref(false)
const AddFormTitle = ref('')
const AddFormId = ref('')
const disabledName = ref('')

const supplierNameOptions = ref<any[]>([])
const supplierNameDate = ref({
    pageNum: 1,
    pageSize: 10,
    supplierName: ''
})
const supplierQueryLoading = ref(false)
const supplierLoading = ref(true)
const supplierNametotal = ref()
const queryLoading = ref(false)

// 部门类型
const departmentTypeList = ref<{ deptId: string; deptName: string; }[]>([])
// 部门名称
const deptList = ref<{ deptId: string; deptName: string; }[]>([])
// 人员名称
const recruiterList = ref<{ userId: string; nickName: string; }[]>([])

const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    styleName: undefined,
    categoryIdList: undefined,
    content: undefined,
    supplierId: undefined,
    groupName: undefined,
    types: undefined,
    recruiterDeptId: undefined,
    recruiterUserId: undefined,
    startTime: '',
    endTime: '',
    inStartTime: '',
    inEndTime: '',
    createStartTime: '',
    createEndTime: '',
    receiveStartTime: '',
    receiveEndTime: '',
    brandName: undefined,
    sellStatus: undefined,
    recipient: undefined
})
// 合同状态
const sellStatusList = ref([
    { label: '未签署', value: 0 },
    { label: '已签署', value: 1 },
])
// 审批通过时间
const putTime = ref()
// 入库时间
const storeTime = ref()
// 创建时间
const createTime = ref()
// 接收时间
const receiveTime = ref()

const tableData = ref([])
const tableTotal = ref(0)

/** 获取类目 */
const getCategoryList = async () => {
    try {
        const res = await getCategoryLists();
        const processedData = renameField(res.data);
        options.value = processedData;
    } catch (error) {
        console.error('Failed to get category list:', error);
        options.value = [];
    }
}
const renameField = (arr: any[]) => {
    return arr.filter(item => item.categoryStatus === 0).map(element => {
        if (element.children) {
            element.children = renameField(element.children);
        }
        return {
            label: element.categoryName,
            value: element.categoryId,
            ...element,
        };
    });
}
/**
 * 部门筛选
 */
const departmentTypeChange = async (type: string, id: string) => {
    deptList.value = []
    recruiterList.value = []
    queryParams.value.recruiterDeptId = undefined
    queryParams.value.recruiterUserId = undefined
    if (id) {
        const res = await getSystemList({ parentId: id })
        if (type === 'init') {
            departmentTypeList.value = res.data
        } else {
            deptList.value = res.data
        }
    }
}

/**
 *  根据招商部获取招商员
 */
const deptChange = async (event: string) => {
    queryParams.value.recruiterUserId = undefined
    if (event) {
        const res = await getUserList({ deptId: event })
        recruiterList.value = res.rows
    } else {
        recruiterList.value = []
    }
}

// 查询列表数据
const getList = async () => {
    try {
        loading.value = true
        let params = {
            ...queryParams.value,
            recruiterDeptId: queryParams.value.recruiterDeptId ? queryParams.value.recruiterDeptId : queryParams.value.types
        }
        let res: any = null
        if (activeTab.value === 'DJS') {
            res = await commissionaireList({ ...params, receiveStatus: 0 })
        } else if (activeTab.value === 'YJS') {
            res = await commissionaireList({ ...params, receiveStatus: 1 })
        } else {
            res = await commissionaireList({ ...params, receiveStatus: 2 })
        }
        tableData.value = res.rows || []
        tableTotal.value = res.total || 0
        loading.value = false
        queryLoading.value = false
    } catch (e) {
    } finally {
        loading.value = false;
    }
}
/** 审批通过时间 */
const pricingPickerChange = (val: string[]) => {
    if (val) {
        queryParams.value.startTime = val[0]
        queryParams.value.endTime = val[1]
    } else {
        queryParams.value.startTime = ''
        queryParams.value.endTime = ''
    }
}
/** 入库时间 */
const storePickerChange = (val: string[]) => {
    if (val) {
        queryParams.value.inStartTime = val[0]
        queryParams.value.inEndTime = val[1]
    } else {
        queryParams.value.inStartTime = ''
        queryParams.value.inEndTime = ''
    }
}
/** 创建时间 */
const createPickerChange = (val: string[]) => {
    if (val) {
        queryParams.value.createStartTime = val[0]
        queryParams.value.createEndTime = val[1]
    } else {
        queryParams.value.createStartTime = ''
        queryParams.value.createEndTime = ''
    }
}
/** 接收时间 */
const receivePickerChange = (val: string[]) => {
    if (val) {
        queryParams.value.receiveStartTime = val[0]
        queryParams.value.receiveEndTime = val[1]
    } else {
        queryParams.value.receiveStartTime = ''
        queryParams.value.receiveEndTime = ''
    }
}
// 获取供应商列表
const getHmSupplierList = async () => {
    supplierLoading.value = true
    const res = await loginSupplierList(supplierNameDate.value)
    const reshandle = res.rows.map((item: any) => (
        {
            label: item.supplierName,
            value: item.id
        }
    ))
    supplierNameOptions.value.push(...reshandle)
    supplierNametotal.value = res.total
    supplierLoading.value = false
}

/** select懒加载 */
const selectLoad = async () => {
    if (supplierNameOptions.value.length < supplierNametotal.value) {
        supplierNameDate.value.pageNum++;
        getHmSupplierList()
    }
}
/** 远程搜索 */
const searchQuery = async (query: string) => {
    supplierQueryLoading.value = true
    supplierNameOptions.value = []
    supplierNameDate.value.pageNum = 1;
    supplierNameDate.value.pageSize = 10
    supplierNameDate.value.supplierName = query
    await getHmSupplierList()
    supplierQueryLoading.value = false
}
/** 清空供应商 */
const handleClear = () => {
    supplierNameDate.value.supplierName = ''
    supplierNameOptions.value = []
    supplierNameDate.value.pageNum = 1;
    supplierNameDate.value.pageSize = 10
    getHmSupplierList()
}
/** 页数变化 */
const paginationChange = async () => {
    await getList();
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
    getColmun()
}
/** 搜索按钮操作 */
const handleQuery = () => {
    queryLoading.value = true
    queryParams.value.pageNum = 1;
    getList();
};
// 商品提交回调函数
const AddFormSubmit = () => {
    isAddDrawer.value = false
    getList()
}
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    queryParams.value.pageNum = 1;
    queryParams.value.categoryIdList = undefined
    handleClear();
    putTime.value = undefined
    queryParams.value.startTime = ''
    queryParams.value.endTime = ''
    storeTime.value = undefined
    queryParams.value.inStartTime = ''
    queryParams.value.inEndTime = ''
    createTime.value = undefined
    queryParams.value.createStartTime = ''
    queryParams.value.createEndTime = ''
    receiveTime.value = undefined
    queryParams.value.receiveStartTime = ''
    queryParams.value.receiveEndTime = ''
    handleQuery();
};
// 直播机制反显
const computedMechanism = (row: any, numbers: string) => {
    if (row) {
        const price = row.price ? row.price : '-'
        const commission = row.commission ? row.commission + '%' : '-'
        const brokerage = row.brokerage ? row.brokerage + '%' : '-'
        const liveStreamingMechanism = row.liveStreamingMechanism ? row.liveStreamingMechanism : '-'
        const costPrice = row.costPrice ? row.costPrice : '-'
        if (row.cooperationMode) {
            if (row.cooperationMode == '分佣') {
                return '机制' + numbers + ': ' + '售价:' + price + ' 佣金:' + commission + ' 补充佣金:' + brokerage + ' 机制:' + liveStreamingMechanism + ' 成本:' + costPrice
            } else {
                return '机制' + numbers + ': ' + '成本:' + costPrice + ' 机制:' + liveStreamingMechanism
            }
        }
    }
}
/** 查看商品详情 */
const handleInfo = (row: any, title: string) => {
    if (title === '查看详情') {
        isAddDrawer.value = true;
        AddFormTitle.value = title
        AddFormId.value = row.productId
        disabledName.value = ''
    } else if (title == '接收') {
        ElMessageBox.confirm('请确认该商品已到仓后进行接收', '确认接收', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            callback: async (action: Action) => {
                if (action == 'confirm') {
                    await commissionaireReceive({ id: row.id, productId: row.productId, auditStatus: row.auditStatus })
                    proxy?.$modal.msgSuccess('接收成功');
                    await getList()
                }
            },
        })
    }
};

/** 获取colmun */
const getColmun = async () => {
    let columnDatas = null
    if (activeTab.value === 'DJS') {
        columnDatas = await proxy?.useColumn('在仓商品管理待接收列表')
    } else if (activeTab.value === 'YJS') {
        columnDatas = await proxy?.useColumn('在仓商品管理已接收列表')
    } else {
        columnDatas = await proxy?.useColumn('在仓商品管理已入库列表')
    }
    commodityManage.value = columnDatas.columnCustom
    columnData.value = columnDatas
    queryParams.value.pageSize = columnDatas.columnPageSize || 10
}
/** 拖拽事件 */
const dragEnd = async (newWidth: number, oldWidth: number, column: any, event: MouseEvent) => {
    columnData.value.columnCustom.map((item: any) => {
        if (item.prop == column.property) {
            item.width = newWidth
        }
    })
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
}
const tabChange = async () => {
    resetQuery()
    await getColmun()
    await getList()
}
onMounted(async () => {
    queryParams.value.pageNum = 1;
    departmentTypeChange('init', '1861962988832542721')
    await getColmun()
    await getList()
    getCategoryList();
})
</script>

<style lang="scss" scoped>
.form_button {
    display: flex;
    justify-content: flex-end;
}

.supplierSelect {
    :deep(.el-popper) {
        left: 0 !important;
        top: 34px !important;
        z-index: 7000 !important;
        width: 100% !important;
    }
}

:deep(.el-tabs__content) {
    overflow: visible !important;
}

.supplierSelect_icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
}

.el-select-loading {
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: initial;
    pointer-events: none;
    color: var(--el-color-info);
    font-size: 12px;

    &__icon {
        font-size: 16px;
        animation: rotate 1.5s linear infinite;
    }

    &__tips {
        margin-left: 6px;
    }

    @keyframes rotate {
        from {
            transform: rotate(0deg);
        }

        to {
            transform: rotate(360deg);
        }
    }
}

.el-select-loading__tips {
    color: #606266;
    font-size: 14px;
}

:deep(.el-card__header) {
    display: flex;
    justify-content: flex-end;
}
</style>